package cn.yangliu.nacos.comm.handler.mvc;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import cn.yangliu.nacos.comm.JsonResult;
import cn.yangliu.nacos.comm.enums.GlobalResultCode;
import cn.yangliu.nacos.comm.ex.GlobalException;
import cn.yangliu.nacos.comm.handler.ExceptionResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * The type Global exception handler.
 *
 * <p>
 * .
 *
 * @author 问道于盲
 * @date 2019 -12-12
 */
@RestControllerAdvice
@Slf4j
@ConditionalOnClass(HttpServletRequest.class)
public class GlobalExceptionHandler implements ExceptionResolver {

    /**
     * current class's static member
     * The constant ACCESS_DENIED_CLASS_NAME.
     */
    private static final String ACCESS_DENIED_CLASS_NAME = "org.springframework.security.access.AccessDeniedException";

    /**
     * Handler json result.
     *
     * @param e the e
     * @return the json result
     */
    @ExceptionHandler(GlobalException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<?> handler(GlobalException e) {
        int code = e.getCode();
        String msg = e.getMessage();
        log.error(e.getMessage(), e);

        return new ResponseEntity<>(JsonResult.getInstance(code, msg), HttpStatus.valueOf(code));
    }

    /**
     * Provides handling for standard Spring MVC exceptions.
     *
     * @param e       the target exception
     * @param request the current request
     * @return the response entity
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            HttpMediaTypeNotAcceptableException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class, TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            MethodArgumentNotValidException.class,
            MissingServletRequestPartException.class, BindException.class,
            NoHandlerFoundException.class, AsyncRequestTimeoutException.class,
            MethodArgumentTypeMismatchException.class, Exception.class})
    public ResponseEntity<Object> handleException(Exception e,
                                                  HttpServletRequest request) {
        log.error(e.getMessage(), e);
        HttpHeaders headers = new HttpHeaders();
        HttpStatus status = null;
        JsonResult<Object> body = null;

        /**
         * if current exception's cause is an instance of SaeException
         *
         * try to get SaeException from current exception's cause
         * and get message from SaeException
         *
         * if not , continue check
         */
        Throwable cause = e.getCause();
        if (Objects.nonNull(cause) && (cause instanceof GlobalException)) {
            status = HttpStatus.BAD_REQUEST;
            GlobalException exception = (GlobalException) cause;
            body = JsonResult.getInstance(exception.getCode(), cause.getMessage());
            return new ResponseEntity<>(body, headers, status);
        }
        /**
         * Handle particular exceptions below
         */
        if (e instanceof HttpRequestMethodNotSupportedException) {
            status = HttpStatus.METHOD_NOT_ALLOWED;
            body = JsonResult.getInstance(GlobalResultCode.METHOD_NOT_ALLOWED);
        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            status = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
            body = JsonResult.getInstance(GlobalResultCode.UNSUPPORTED_MEDIA_TYPE);
        } else if (e instanceof HttpMediaTypeNotAcceptableException) {
            status = HttpStatus.NOT_ACCEPTABLE;
            body = JsonResult.getInstance(GlobalResultCode.UNSUPPORTED_MEDIA_TYPE);
        } else if (e instanceof MissingPathVariableException
                || e instanceof ConversionNotSupportedException
                || e instanceof HttpMessageNotWritableException) {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            body = JsonResult.getInstance(GlobalResultCode.PARAM_IS_INVALID);
        } else if (e instanceof MissingServletRequestParameterException) {
            status = HttpStatus.BAD_REQUEST;
            body = JsonResult.getInstance(GlobalResultCode.PARAM_IS_BLANK);
        } else if (e instanceof ServletRequestBindingException
                || e instanceof HttpMessageNotReadableException
                || e instanceof MethodArgumentTypeMismatchException) {
            status = HttpStatus.BAD_REQUEST;
            body = JsonResult.getInstance(GlobalResultCode.PARAM_IS_INVALID);
        } else if (e instanceof TypeMismatchException) {
            status = HttpStatus.BAD_REQUEST;
            body = JsonResult.getInstance(GlobalResultCode.PARAM_TYPE_BIND_ERROR);
        } else if (e instanceof BindException) {
            status = HttpStatus.BAD_REQUEST;
            body = handleBindingResult(((BindException) e).getBindingResult());
        } else if (e instanceof MethodArgumentNotValidException) {
            status = HttpStatus.BAD_REQUEST;
            body = handleBindingResult(
                    ((MethodArgumentNotValidException) e).getBindingResult());
        } else if (e instanceof MissingServletRequestPartException) {
            status = HttpStatus.BAD_REQUEST;
            body = JsonResult.getInstance(GlobalResultCode.INTERFACE_ADDRESS_NOT_FOUND);
        } else if (e instanceof NoHandlerFoundException) {
            status = HttpStatus.NOT_FOUND;
            body = JsonResult.getInstance(GlobalResultCode.INTERFACE_ADDRESS_NOT_FOUND);
        } else if (e instanceof AsyncRequestTimeoutException) {
            status = HttpStatus.SERVICE_UNAVAILABLE;
            body = JsonResult.getInstance(GlobalResultCode.INTERFACE_REQUEST_TIMEOUT);
        } else if (e instanceof EmptyResultDataAccessException) {
            status = HttpStatus.NOT_FOUND;
            body = JsonResult.getInstance(GlobalResultCode.DATA_NOT_EXIST);
        } else if (Objects.equals(e.getClass().getName(),
                ACCESS_DENIED_CLASS_NAME)) {
            status = HttpStatus.FORBIDDEN;
            body = JsonResult.getInstance(GlobalResultCode.ACCESS_DENIED);
        } else {
            /**
             * Unknown exception, typically a wrapper with a common MVC
             * exception as cause (since @ExceptionHandler type declarations
             * also match first-level causes):
             * We only deal with top-level MVC exceptions here, so let's just
             * return 500 HTTP status
             */
            status = getStatus(request);
            body = httpStatusToSaeResult(status);
        }
        return new ResponseEntity<>(body, headers, status);
    }

    /**
     * current class method for getter.
     * Gets status.
     *
     * @param request the request
     * @return the status
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

}